package com.yjq.programmer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjq.programmer.bean.CodeMsg;
import com.yjq.programmer.dao.AlbumCategoryMapper;
import com.yjq.programmer.dao.AlbumMapper;
import com.yjq.programmer.dao.MusicMapper;
import com.yjq.programmer.dao.SingerMapper;
import com.yjq.programmer.domain.*;
import com.yjq.programmer.dto.AlbumCategoryDTO;
import com.yjq.programmer.dto.AlbumDTO;
import com.yjq.programmer.dto.PageDTO;
import com.yjq.programmer.dto.ResponseDTO;
import com.yjq.programmer.service.IAlbumService;
import com.yjq.programmer.utils.CommonUtil;
import com.yjq.programmer.utils.CopyUtil;
import com.yjq.programmer.utils.UuidUtil;
import com.yjq.programmer.utils.ValidateEntityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 杨杨吖
 * @QQ 823208782
 * @WX yjqi12345678
 * @create 2022-11-14 8:58
 */
@Service
@Transactional
public class AlbumServiceImpl implements IAlbumService {

    @Resource
    private AlbumMapper albumMapper;

    @Resource
    private AlbumCategoryMapper albumCategoryMapper;

    @Resource
    private SingerMapper singerMapper;

    @Resource
    private MusicMapper musicMapper;

    /**
     * 分页获取专辑数据
     * @param pageDTO
     * @return
     */
    @Override
    public ResponseDTO<PageDTO<AlbumDTO>> getAlbumListByPage(PageDTO<AlbumDTO> pageDTO) {
        AlbumExample albumExample = new AlbumExample();
        // 判断是否进行关键字搜索
        AlbumDTO searchAlbumDTO = pageDTO.getSearchEntity();
        AlbumExample.Criteria criteria = albumExample.createCriteria();
        if(!CommonUtil.isEmpty(searchAlbumDTO.getName())) {
            criteria.andNameLike("%" + searchAlbumDTO.getName() + "%");
        }
        // 不知道当前页多少，默认为第一页
        if(pageDTO.getPage() == null){
            pageDTO.setPage(1);
        }
        if(pageDTO.getSize() == null) {
            pageDTO.setSize(5);
        }
        albumExample.setOrderByClause("create_time desc");
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        // 分页查出专辑数据
        List<Album> albumList = albumMapper.selectByExample(albumExample);
        PageInfo<Album> pageInfo = new PageInfo<>(albumList);
        // 获取数据的总数
        pageDTO.setTotal(pageInfo.getTotal());
        // 将domain类型数据  转成 DTO类型数据
        List<AlbumDTO> albumDTOList = CopyUtil.copyList(albumList, AlbumDTO.class);
        for(AlbumDTO albumDTO : albumDTOList) {
            AlbumCategory albumCategory = albumCategoryMapper.selectByPrimaryKey(albumDTO.getAlbumCategoryId());
            if(null != albumCategory) {
                albumDTO.setAlbumCategoryDTO(CopyUtil.copy(albumCategory, AlbumCategoryDTO.class));
            } else {
                albumDTO.setAlbumCategoryDTO(new AlbumCategoryDTO());
            }
        }
        pageDTO.setList(albumDTOList);
        return ResponseDTO.success(pageDTO);
    }

    /**
     * 保存专辑数据(添加、修改)
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> saveAlbum(AlbumDTO albumDTO) {
        // 进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(albumDTO);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDTO.errorByMsg(validate);
        }
        Album album = CopyUtil.copy(albumDTO, Album.class);
        Singer singer = singerMapper.selectByPrimaryKey(album.getSingerId());
        if(null == singer) {
            return ResponseDTO.errorByMsg(CodeMsg.SINGER_NOT_EXIST);
        }
        album.setSingerPhoto(singer.getHeadPic());
        album.setSingerName(singer.getName());
        if(CommonUtil.isEmpty(album.getId())){
            // id为空 说明是添加数据
            // 判断该歌手的专辑是否存在
            if(isAlbumExist(album, "")){
                return ResponseDTO.errorByMsg(CodeMsg.ALBUM_CONTENT_EXIST);
            }
            // 生成8位id
            album.setId(UuidUtil.getShortUuid());
            album.setCreateTime(new Date());
            // 添加数据到数据库
            if(albumMapper.insertSelective(album) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.ALBUM_ADD_ERROR);
            }
        }else{
            // id不为空 说明是修改数据
            // 判断该歌手的专辑是否存在
            if(isAlbumExist(album, album.getId())){
                return ResponseDTO.errorByMsg(CodeMsg.ALBUM_CONTENT_EXIST);
            }
            // 修改数据库中数据
            if(albumMapper.updateByPrimaryKeySelective(album) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.ALBUM_EDIT_ERROR);
            }
            Album albumDB = albumMapper.selectByPrimaryKey(album.getId());
            // 同步更新音乐中的专辑信息
            MusicExample musicExample = new MusicExample();
            musicExample.createCriteria().andAlbumIdEqualTo(albumDB.getId());
            Music music = new Music();
            music.setAlbumName(albumDB.getName());
            musicMapper.updateByExampleSelective(music, musicExample);
        }
        return ResponseDTO.successByMsg(true, "保存成功！");
    }

    /**
     * 删除专辑数据
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> removeAlbum(AlbumDTO albumDTO) {
        if(CommonUtil.isEmpty(albumDTO.getId())){
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        // 删除专辑信息
        if(albumMapper.deleteByPrimaryKey(albumDTO.getId()) == 0){
            return ResponseDTO.errorByMsg(CodeMsg.ALBUM_DELETE_ERROR);
        }
        return ResponseDTO.successByMsg(true, "删除成功！");
    }

    /**
     * 获取全部专辑数据
     * @return
     */
    @Override
    public ResponseDTO<List<AlbumDTO>> getAllAlbum() {
        AlbumExample albumExample = new AlbumExample();
        List<Album> albumList = albumMapper.selectByExample(albumExample);
        return ResponseDTO.success(CopyUtil.copyList(albumList, AlbumDTO.class));
    }

    /**
     * 根据专辑分类id获取专辑数据
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<List<AlbumDTO>> getAlbumByCategoryId(AlbumDTO albumDTO) {
        if(CommonUtil.isEmpty(albumDTO.getAlbumCategoryId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        AlbumExample albumExample = new AlbumExample();
        if(!"0".equals(albumDTO.getAlbumCategoryId())) {
            albumExample.createCriteria().andAlbumCategoryIdEqualTo(albumDTO.getAlbumCategoryId());
        }
        List<Album> albumList = albumMapper.selectByExample(albumExample);
        return ResponseDTO.success(CopyUtil.copyList(albumList, AlbumDTO.class));
    }

    /**
     * 根据id获取专辑数据
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<AlbumDTO> getById(AlbumDTO albumDTO) {
        if(CommonUtil.isEmpty(albumDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        Album album = albumMapper.selectByPrimaryKey(albumDTO.getId());
        AlbumCategory albumCategory = albumCategoryMapper.selectByPrimaryKey(album.getAlbumCategoryId());
        AlbumDTO albumDTODB = CopyUtil.copy(album, AlbumDTO.class);
        if(albumCategory == null) {
            albumDTODB.setAlbumCategoryDTO(new AlbumCategoryDTO());
        } else {
            albumDTODB.setAlbumCategoryDTO(CopyUtil.copy(albumCategory, AlbumCategoryDTO.class));
        }
        return ResponseDTO.success(albumDTODB);
    }

    /**
     * 搜索专辑数据
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<List<AlbumDTO>> searchAlbum(AlbumDTO albumDTO) {
        AlbumExample albumExample = new AlbumExample();
        if(!CommonUtil.isEmpty(albumDTO.getName())) {
            albumExample.createCriteria().andNameLike("%" + albumDTO.getName() + "%");
        }
        albumExample.setOrderByClause("create_time desc");
        List<Album> albumList = albumMapper.selectByExample(albumExample);
        return ResponseDTO.success(CopyUtil.copyList(albumList, AlbumDTO.class));
    }

    /**
     * 专辑浏览量增加
     * @param albumDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> addAlbumView(AlbumDTO albumDTO) {
        if(CommonUtil.isEmpty(albumDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        Album album = albumMapper.selectByPrimaryKey(albumDTO.getId());
        if(album == null) {
            return ResponseDTO.errorByMsg(CodeMsg.ALBUM_NOT_EXIST);
        }
        album.setViewNum(album.getViewNum() + 1);
        albumMapper.updateByPrimaryKeySelective(album);
        return ResponseDTO.success(true);
    }

    /**
     * 获取热门专辑数据
     * @param pageDTO
     * @return
     */
    @Override
    public ResponseDTO<List<AlbumDTO>> getHotAlbumList(PageDTO<AlbumDTO> pageDTO) {
        AlbumExample albumExample = new AlbumExample();
        albumExample.setOrderByClause("view_num desc");
        if(pageDTO.getSize() != null && pageDTO.getPage() != null) {
            PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        }
        List<Album> albumList = albumMapper.selectByExample(albumExample);
        return ResponseDTO.success(CopyUtil.copyList(albumList, AlbumDTO.class));
    }

    /**
     * 获取专辑的总数
     * @return
     */
    @Override
    public ResponseDTO<Integer> getAlbumTotal() {
        return ResponseDTO.success(albumMapper.countByExample(new AlbumExample()));
    }

    /**
     * 判断该歌手的专辑是否存在
     * @param album
     * @param id
     * @return
     */
    public Boolean isAlbumExist(Album album, String id) {
        AlbumExample albumExample = new AlbumExample();
        albumExample.createCriteria().andSingerIdEqualTo(album.getSingerId()).andNameEqualTo(album.getName());
        List<Album> selectedAlbumList = albumMapper.selectByExample(albumExample);
        if(selectedAlbumList != null && selectedAlbumList.size() > 0) {
            if(selectedAlbumList.size() > 1){
                return true; //出现重名
            }
            if(!selectedAlbumList.get(0).getId().equals(id)) {
                return true; //出现重名
            }
        }
        return false;//没有重名
    }


}
